package main.singleton;

/**
 * @Author: SerMs
 * @Date: 2024/06/17 17 25
 * @Email: 1839928782@qq.com
 * @Blog: https://serms.top
 * 静态内部类的方式实现
 * JVM来保证单例
 * 加载外部类时不会加载内部类,只有调用到内部类的方法时内部类才会被创建
 **/
public class Singleton07 {
    private Singleton07() {
        if (SingletonHandler.instance != null) {
            throw new RuntimeException("不允许非法访问");
        }
    }

    private static class SingletonHandler {
        private static Singleton07 instance = new Singleton07();
    }

    public static Singleton07 getInstance() {
        return SingletonHandler.instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            // 多线程
            new Thread(() ->
                    System.out.println(SingletonHandler.instance.hashCode())
            ).start();
        }
    }
}
